<template>
  <el-card shadow="hover">
    <!-- 按钮 -->
    <el-button type="primary" :icon="Plus" style="color: crimson; margin-right: 15px"
      @click="addTrademark">添加品牌</el-button>
    <el-badge :value="records.length">
      <el-button type="primary" :icon="Download" @click="exportExcel">导出此页面</el-button>
    </el-badge>
    <!-- 表格 -->
    <el-table :data="records" stripe style="margin-top: 20px;" border>
      <el-table-column type="index" label="序号" align="center" width="86px" />
      <el-table-column prop="tmName" label="品牌名称" align="center" />
      <el-table-column label="品牌LOGO" align="center">
        <template #="{ row, a }">
          <img :src="row.logoUrl" alt="" style=" height: 85px; width: 100px; border-radius: 10px;" />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作" align="center">
        <template #='{ row, $index }'>
          <el-button type="warning" :icon="Edit" @click="Updatemark(row)">编辑</el-button>
          <el-popconfirm width="220" cancel-button-text="取消" confirm-button-text="确定" :icon="WarningFilled"
            @confirm='DeleteMark(row.id)' icon-color="#626AEF" :title="`你确定要删除  ${row.tmName}  吗`">
            <template #reference>
              <el-button type="danger" :icon="Delete">删除</el-button>
            </template>
          </el-popconfirm>

        </template>

      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination v-model:current-page="pageno" v-model:page-size="pageSize" :page-sizes="[3, 5, 7, 9]"
      :background="true" layout=" prev, pager, next,jumper,->,total, sizes," :total="total" style="margin: 30px 1px"
      @current-change="getTrademark" @size-change="SizeHandle" />

    <!-- 对话框 -->
  </el-card>
  <el-dialog v-model="dialogVist" :title="Trademarkdata.id ? '更新品牌' : '添加品牌'">
    <el-form label-width="120px" :model="Trademarkdata" :rules="rules" ref="formRef">
      <!-- 添加品牌名称 -->
      <el-form-item label="品牌名称" prop="tmName">
        <el-input placeholder="请输入添加品牌的名称" v-model="Trademarkdata.tmName" style="width: 80%"></el-input>
      </el-form-item>
      <!-- 上传图片 -->
      <el-form-item label="品牌LOGO" v-model="Trademarkdata.logoUrl" prop="logoUrl">
        <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
          :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
          <img v-if="Trademarkdata.logoUrl" :src="Trademarkdata.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>

    <!-- 对话框底部的具名插槽:按钮 -->
    <template #footer>
      <el-button @click="dialogVist = false">取消</el-button>
      <el-button type="success" @click="addMark">确定</el-button>
    </template>
  </el-dialog>

  <!-- pageno:当前为第几页  pageSize:一页有几条数据  page-sizes:可选每页有几条数据  background:当前页码的背景颜色
       total:总共多少条数据  @current-change：切换页码数的自定义事件    @size-change：当pagesize发生变化的自定义事件
  -->
</template>

<script setup lang="ts">
import * as XLSX from 'xlsx';
import { Plus, Download, Delete, Edit, WarningFilled } from '@element-plus/icons-vue';
import { ElMessage, type UploadProps } from 'element-plus';
import { ref, onMounted, nextTick } from 'vue';
import type { TrademarkAllData, TrademarkList, Trademark } from '@/api/product/trademark/types/index';
// 引入发请求函数
import { reqTrademarkList, reqAddOrUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark/index';
// 默认当前页面为第一页
let pageno = ref(1);
// 默认一页里有3条数据
let pageSize = ref(3);
// 定义总条数据
let total = ref<number>(0);
// 定义表格数据结构
let records = ref<TrademarkList>([]);
// 控制品牌与更新的对话框现实与隐藏
let dialogVist = ref<boolean>(false);
// 收集新增品牌的数据
let Trademarkdata = ref<Trademark>({
  tmName: '', //收集品牌名称
  logoUrl: '', //收集品牌图片
});
// 获取from组件实例
let formRef = ref<any>();
// 
let yourDataArray = ref([])




// 声明方法发送请求(携带pageno和pageSize)
const getTrademark = async () => {
  let res: TrademarkAllData = await reqTrademarkList(pageno.value, pageSize.value);
  //赋值为请求回来的数据
  total.value = res.total;
  records.value = res.records;
  //  console.log(res)
};

// 组件挂载完毕
onMounted(() => {
  // 调用函数发请求
  getTrademark();
});
// 点击切换页码发送请求获取最新数据
// const currentHandle = (value:number)=>{
//     pageno.value = value
//     getTrademark()
// }

// 点击切换pagesize的回调
const SizeHandle = (value: number) => {
  // 点击切换
  pageSize.value = value;
  // 让当前页面数归1
  pageno.value = 1;
  // 发送请求获取最新数据
  getTrademark();
  // console.log(value)
};

// 添加按钮的回调
let addTrademark = () => {
  // 下次点击按钮的时候把之前的数据清空
  Trademarkdata.value.tmName = '';
  Trademarkdata.value.logoUrl = '';
  Trademarkdata.value.id = 0
  // 点击按钮展示弹框
  dialogVist.value = true;
  nextTick(() => {
    // nextTick用于获取最新的dom(在更新完的最新dom上,将之前的数据清空)
    formRef.value.clearValidate('tmName');
    formRef.value.clearValidate('logoUrl');
  });
};

// 导出Excle表格
const exportExcel = () => {
  // 创建一个工作簿对象
  const workbook = XLSX.utils.book_new();

  // 创建一个工作表对象
  const worksheet = XLSX.utils.json_to_sheet(records.value);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  // 将工作簿保存为Excel文件
  XLSX.writeFile(workbook, 'filename.xlsx');
}


// 在上传图片前对图片限制的回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // 如果文件类型为jpeg或png或gif 均可上传
  if (
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
    // 限制文件大小
    if (rawFile.size / 1024 / 1024 < 2) {
      return true;
    } else {
      // 上传文件过大
      ElMessage({
        type: 'error',
        message: '上传内容过大',
      });
      return false
    }
  }
};

// 图片上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  // console.log(response.data)
  // 收集用户添加图片的url地址
  Trademarkdata.value.logoUrl = response.data;
  // 清楚表单校验错误信息
  formRef.value.clearValidate('logoUrl');
};
// 添加品牌的回调
let addMark = async () => {
  await formRef.value.validate()
  // 收集参数为:Trademarkdata.tmName 和 Trademarkdata.logourl
  reqAddOrUpdateTrademark(Trademarkdata.value).then(
    () => {
      // 成功的回调 1.关闭弹框 2.发请求获取页面最新数据
      dialogVist.value = false;
      // 调用函数获取最新数据
      getTrademark();
      // 成功后的消息提示
      ElMessage({
        type: 'success',
        message: '恭喜你上传成功!!',
      });
    }
  )
    .catch(() => {
      // 失败的回调(错误消息提示)
      ElMessage({
        type: 'error',
        message: '上传失败,请稍后重试!!',
      });
    });
};

// 校验品牌名字
let validatorTmName = (
  rules: any,
  value: any,
  callBack: any
) => {
  // 判断品牌名称长度必须大于2
  if (value.length >= 2) {
    callBack();
  } else {
    callBack(new Error('请输入品牌名称'))
  }
};
// [校验品牌图片
let validatorLogoUrl = (
  rules: any,
  value: any,
  callBack: any
) => {
  // 图片地址至少不等于0
  if (value.length) {
    callBack();
  } else {
    callBack(new Error('请填写品牌图片'))
  }
};

// 表单校验规则对象
let rules = {
  tmName: [
    // require:为true必须校验  trigger:触发的时机:change或blur validator:校验的具体规则
    {
      required: true,
      trigger: 'blur',
      validator: validatorTmName,
    },
  ],
  logoUrl: [
    { required: true, validator: validatorLogoUrl },
  ],
};

// 点击编辑的回调
let Updatemark = (row: Trademark) => {
  // 显示弹框
  dialogVist.value = true
  // 获取将要修改的品牌
  Trademarkdata.value.tmName = row.tmName;
  Trademarkdata.value.logoUrl = row.logoUrl;
  Trademarkdata.value.id = row.id
}

// 点击删除的回调
let DeleteMark = (id: number) => {
  // 发请求删除品牌(根据id参数)
  reqDeleteTrademark(id).then(() => {
    // 发请求获取最新页面
    getTrademark();
  }).catch(() => {
    ElMessage({
      type: 'error',
      message: "删除失败,请稍后重试"
    })
  })
}



</script>

<script lang="ts">
export default {
  name: 'Trademark',
};
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
